﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Recognition;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 测试语音识别02
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private SpeechRecognitionEngine _recognizer;

        public MainWindow()
        {
            InitializeComponent();
            InitializeSpeechRecognition();
        }

        private void InitializeSpeechRecognition()
        {
            _recognizer = new SpeechRecognitionEngine();

            // 添加语音识别的事件处理程序
            _recognizer.SpeechRecognized += Recognizer_SpeechRecognized;

            // 定义语音识别的语法
            Choices commands = new Choices();
            commands.Add(new string[] { "你好", "再见", "开始", "停止", "帮助" });

            GrammarBuilder gb = new GrammarBuilder();
            gb.Append(commands);
            Grammar grammar = new Grammar(gb);

            _recognizer.LoadGrammar(grammar);
            _recognizer.SetInputToDefaultAudioDevice(); // 使用默认音频输入设备
        }

        private void StartRecognitionButton_Click(object sender, RoutedEventArgs e)
        {
            _recognizer.RecognizeAsync(RecognizeMode.Multiple); // 开始异步识别
        }

        private void Recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            SpeechTextBox.Text += e.Result.Text + Environment.NewLine; // 将识别结果添加到文本框
        }

        protected override void OnClosed(EventArgs e)
        {
            _recognizer.Dispose(); // 释放资源
            base.OnClosed(e);
        }
    }
}
